<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>多物体运动</title>
		<style>
			*{
				padding: 0%;
				margin: 0;
			}
			div{
				width: 350px;
				height: 150px;
				background-color: royalblue;
				margin: 20px 0;
				border: 4px solid #000;
			}
		</style>
	</head>
	<body>
		<div></div>
		<div></div>
		<div></div>
	</body>
	<script>
		
					window.onload = function() {
						var allBoxs = document.getElementsByTagName('div');
						for (var i = 0; i < allBoxs.length; i++) {
							allBoxs[i].onmouseover = function() {
								startAnimation(this, 600);
							}
							allBoxs[i].onmouseout = function() {
								startAnimation(this, 300);
							}
						}
						var speed = 0;
		
						function startAnimation(obj, endTarget) {
							// 针对于多物体运动,定时器的返回值要绑定当前的对象中.
							clearInterval(obj.timer);
							obj.timer = setInterval(function(){
								let cur = parseInt(getStyle(obj,'width'));
								speed = (endTarget - cur) / 20;
								speed = endTarget > cur ? Math.ceil(speed) : Math.floor(speed);
								if(endTarget === cur) {
									clearInterval(obj.timer);
									return;
								}
								obj.style.width = cur + speed + 'px';
							},30);
						}
						/**
						 * 获取元素属性的函数
						 * @param {Object} obj 当前元素对象
						 * @param {Object} attr 当前元素对象的属性
						 */
						function getStyle(obj, attr) {
							if (obj.currentStyle) {
								// 兼容ie
								return obj.currentStyle[attr];
							} else {
								// 兼容主流浏览器
								return getComputedStyle(obj, null)[attr];
							}
						}
					}
		
	</script>
</html>